import { to } from '@/tools'

export type RequestFn<P = Record<string, any>, T = any> = (
  params: P,
) => Promise<HttpResult.ResponseData<T>>

interface params<P = Record<string, any>, T = any> {
  request: RequestFn<P, T>
  isInit?: boolean // 是否初始化加载
  getParams?: (options?: AnyObject) => P
  follow?: (source: T) => void
  errorFn?: (err: HttpResult.ResponseData<unknown>) => void
}

export const useReq = <P = Record<string, any>, T = Record<string, any>>({
  request,
  isInit,
  getParams,
  follow,
  errorFn,
}: params<P, T>) => {
  const source = ref<T>();
  const loading = ref(false);
  const queryDate = async (param: P) => {
    loading.value = true;
    const [err, res] = await to(request(param));
    loading.value = false;
    if (err || !res) {
      errorFn?.(err);
      return
    }
    source.value = res.data;
    res.data && follow?.(res.data);
  }

  onLoad((options) => {
    if (isInit) {
      queryDate((getParams ? getParams(options) : {}) as unknown as P);
    }
    else {
      source.value = {} as unknown as T;
    }
  });

  // queryDate 命名错误
  return { source, queryDate, queryData: queryDate, loading };
}
